package com.zunipe.accounts.database.handler;

import com.zunipe.accounts.AccountApplication;
import com.zunipe.accounts.database.Result;
import com.zunipe.accounts.database.dao.UserDao;
import com.zunipe.accounts.database.entity.User;

public class LoginHandler {
    private final UserDao userDao;

    public LoginHandler() {
        userDao = AccountApplication.getInstance().getUserDao();
    }

    public Result tryLogin(User user) {
        User findUser = userDao.findByUsername(user.getUsername());
        if (findUser == null)
            return new Result(Result.FAILED_CODE, "用户不存在");
        if (!findUser.getPassword().equals(user.getPassword()))
            return new Result(Result.FAILED_CODE, "用户名或密码错误");
        AccountApplication.getInstance().setUsername(findUser);
        return new Result(Result.SUCCESS_CODE, "登录成功");
    }

    public Result register(User user) {
        User findUser = userDao.findByUsername(user.getUsername());
        if (findUser != null)
            return new Result(Result.FAILED_CODE, "用户已存在");
        userDao.insert(user);
        return new Result(Result.SUCCESS_CODE, "注册成功");
    }
}
